import localDB from "./local_db";
import store from "../store"

let dbName = "music-app";
let dbVersion = 1;
let storeName = "storage";

export default {
    setItem(key, value) {
        return new Promise((resolve, reject) => {
            let inert = (db, storeName, key, value, objectStore) => {
                localDB.searchById(db, storeName, key).then(ret => {
                    localDB.deleteById(db, storeName, key).then(ret => {
                        localDB.insert(db, storeName, { id: key, content: value }, objectStore || null).then(ret => {
                            resolve(ret);
                        }, err => {
                            reject(err);
                        });
                    }, err => {
                        reject(err);
                    });
                }, err => {
                    localDB.insert(db, storeName, { id: key, content: value }, objectStore || null).then(ret => {
                        resolve(ret);
                    }, err => {
                        reject(err);
                    });
                });
            }
            localDB.openIndexedDB(dbName, dbVersion).then(ret => {
                let db = ret.db;
                if (ret.type == "onupgradeneeded") {
                    var objectStore = localDB.createObjectStore(db, storeName, "id");
                    inert(db, storeName, key, value, objectStore);
                } else {
                    inert(db, storeName, key, value);
                }
            }, err => {
                reject(err);
            });
        });
    },
    getItem(key) {
        return new Promise((resolve, reject) => {
            localDB.openIndexedDB(dbName, dbVersion).then(ret => {
                let db = ret.db;
                if (ret.type == "onupgradeneeded") {
                    localDB.createObjectStore(db, storeName, "id");
                }
                localDB.searchById(db, storeName, key).then(ret => {
                    resolve(ret.content)
                }, err => {
                    reject(err);
                });
            }, err => {
                reject(err);
            });
        });
    }
}